<template>
  <div class="order">
    <div class="container">
      <div class="header">
        <div class="dateSelect">
          <el-date-picker v-model="dateValue"
                          type="daterange"
                          range-separator="~"
                          start-placeholder="开始日期"
                          end-placeholder="结束日期"
                          :default-time="[,'23:59:59']"
                          @change="getDate">
          </el-date-picker>
        </div>
        <div>
          <el-select v-model="customerValue"
                     placeholder="请选择客户"
                     @change="choiceCustomer"
                     class="mr20" clearable>
            <el-option v-for="item in customerList"
                       :key="item.id"
                       :label="item.name"
                       :value="item.id">
            </el-option>
          </el-select>
          <el-select v-model="productValue"
                     placeholder="请选择产品"
                     @change="choiceProduct"
                     class="mr20" clearable>
            <el-option v-for="item in productList"
                       :key="item.id"
                       :label="item.name"
                       :value="item.id">
            </el-option>
          </el-select>
          <el-input class="ipt"
                    v-model="input"
                    placeholder="请输入订单名称、开单人"></el-input>
          <el-button type="primary"
                     @click="search"
                     icon="el-icon-search">搜索
          </el-button>
          <el-button type="primary"
                     @click="openAddorder"
                     icon="el-icon-plus">创建订单
          </el-button>
          <div class="result lh2">
            <span class="pl20">查询结果:</span>
            <span class="pl20">限制机器总数：<i>{{orderList.num}}台</i></span>
            <span class="pl20">订单总金额：<i>{{orderList.price}}元</i></span>
          </div>
        </div>
      </div>
      <div class="main">
        <gl-table :columns='list'
                  :data="lists"
                  class="gl-table"
                  @button="changeButton">
        </gl-table>
        <gl-pagination :total='totals'
                       class="page"
                       :curr="curr"
                       :size="limits"
                       @callback='changePage'></gl-pagination>
      </div>
      <!--新增订单弹窗-->
      <el-dialog :visible.sync="orderDio"
                 class="w75 mlr-auto"
                 @close='closeDialog'>
        <span slot="title"
              style="fontSize:14px;">{{num!=1?'新增订单':'编辑订单'}}</span>
        <div class="orderform">

          <gl-form :form='form'
                   :form-label='formLabel'
                   :must="must"
                   :rule='rule'
                   ref='form'
                   @change="formSelectChange">
            <div slot="num">
              <el-input type="number"
                        v-model="form.price"
                        placeholder="请输入">
                <template slot="append">元</template>
              </el-input>
            </div>
          </gl-form>
        </div>
        <span slot="footer">
          <el-button @click="orderDio = false">取 消</el-button>
          <el-button type="primary"
                     @click="addOrder">确 定</el-button>
        </span>
      </el-dialog>
      <gldelbtn :show="isShow"
                :text='text'
                @cancel="canceled"
                @determine='defineCallback'></gldelbtn>
    </div>
  </div>
</template>

<script>
  import tools from '../../../mixins/tools/index'
  import {mapGetters} from 'vuex'

  export default {
    name: 'Order',
    components: {},
    data() {
      return {
        productList: [{name: '全部', id: '0'}],
        customerList: [{name: '全部', id: '0'}],
        customerValue: '',
        productValue: '',
        dateValue: '',
        listParams: {
          start_time: '',
          end_time: ''
        },
        input: '',
        lists: [],
        list: [
          {label: '订单ID', prop: 'order_id'},
          {label: '订单名称', prop: 'order_name'},
          {label: '客户', prop: 'customer_name'},
          {label: '所属产品', prop: 'product_name'},
          {label: '开单人', prop: 'contacts'},
          {label: '限制机器数量', prop: 'num'},
          {label: '单价', prop: 'price'},
          {label: '订单总金额', prop: 'total'},
          {label: '订单时间', prop: 'create_time'},
          {label: '操作', prop: '', btns: ['编辑', '删除']}
        ],
        orderDio: false, // 订单弹窗
        form: {},
        formLabel: [
          {
            label: '下单客户:',
            prop: 'customer_id',
            options: []
          },
          {
            label: '选择产品:',
            prop: 'product_id',
            options: []
          },
          {
            label: '订单名称:',
            prop: 'order_name',
            inputType: 'text',
            placeholder: '请输入'
          },
          {
            label: '产品单价:',
            prop: 'price',
            slot: 'num',
            placeholder: '请输入'
          },
          {
            label: '限制机器数量:',
            prop: 'num',
            inputType: 'Number',
            placeholder: '请输入'
          },
          {
            label: '关联合同:',
            prop: 'customer_contract_id',
            options: []
          },
          {
            label: '开单人:',
            prop: 'contacts',
            inputType: 'text',
            placeholder: '请输入'
          }
        ],
        must: ['order_name', 'num'],
        rule: {
          price: [
            {required: true, message: '请输入产品单价:', trigger: 'blur'}
          ],
          customer_id: [
            {required: true, message: '请选择下单客户:', trigger: 'change'}
          ],
          product_id: [
            {required: true, message: '请选择产品:', trigger: 'change'}
          ]
        },
        orderList: '',
        totals: '',
        curr: 1,
        limits: 10,
        num: '',
        order_id: '',
        isShow: false,
        text: '',
        dialogProduct: ''
      }
    },
    computed: {
      ...mapGetters(['userInfo'])
    },
    watch: {
      input() {
        if (!this.input) {
          this.getOrderList()
        }
      },
      num() {
        if (this.num == '') {
          this.form = {}
        }
      },
     
    },
    methods: {
      // 订单列表
      getOrderList() {
        let params = {
          company_id: this.userInfo.company_id,
          curr: this.curr,
          limits: this.limits,
          customer_id: this.customerValue,
          product_id: this.productValue,
          start_time: this.listParams.start_time,
          end_time: this.listParams.end_time,
          keyword: this.input
        }
        this.http
          .$post('admin/order.api/list_order', params, {loading: true})
          .then(res => {
            this.totals = res.total
            this.orderList = res
            let arr = res.list
            arr.map(val => {
              if (val.contacts == '') {
                val.contacts = '无'
              }
              val.create_time = tools.formatDate(val.create_time)
            })
            this.lists = arr
          })
          .catch(err => {
            this.$message.error(err.msg)
          })
      },
      // 分页
      changePage(val) {
        this.curr = val.curr
        this.limits = val.size
        this.getOrderList()
      },

      // 新建订单
      openAddorder() {
        this.num = ''
        this.orderDio = true
        this.$nextTick(() => {
          this.form = {}
          this.$refs.form.resetFields()
          this.formLabel[1].options = []
        })
      },
      // 操作
      changeButton(val) {
        this.order_id = val.row.order_id
        if (val.index == 0) {
          // console.log('编辑')
          this.orderDio = true
          this.num = 1
          let new_form = Object.assign({}, val.row)
          if (new_form.customer_contract_id == 0) {
            new_form.customer_contract_id = ''
          }
          if (new_form.contacts == '无') {
            new_form.contacts = ''
          }
          this.form = new_form

          this.getDialogProduct()
          this.getContract()
        } else {
          // console.log('删除')
          this.text = val.row.order_name
          this.isShow = true
        }
      },
      // 确定
      addOrder() {
        if (this.$refs.form.validate()) {
          if (this.form.price == 0) {
            this.$message({
              message: '价格不能为0',
              type: 'warning'
            })
          } else if (this.num == 1) {
            this.subEdit()
          } else {
            this.subOrderList()
          }
        }
      },
      // 添加订单
      subOrderList() {
        let params = {
          order_name: this.form.order_name,
          customer_id: this.form.customer_id,
          product_id: this.form.product_id,
          price: this.form.price,
          num: this.form.num,
          customer_contract_id: this.form.customer_contract_id,
          contacts: this.form.contacts
        }
        this.http
          .$post('admin/order.api/save_order', params)
          .then(res => {
            this.$message({
              message: '添加成功',
              type: 'success'
            })
            this.orderDio = false
            this.getOrderList()
          })
          .catch(err => {
            this.$message.error(err.msg)
          })
      },
      // 编辑订单
      subEdit() {
        let params = {
          order_id: this.order_id,
          order_name: this.form.order_name,
          customer_id: this.form.customer_id,
          product_id: this.form.product_id,
          price: this.form.price,
          num: this.form.num,
          customer_contract_id: this.form.customer_contract_id,
          contacts: this.form.contacts
        }
        this.http
          .$post('admin/order.api/save_order', params)
          .then(res => {
            this.$message({
              message: '修改成功',
              type: 'success'
            })
            this.orderDio = false
            this.getOrderList()
          })
          .catch(err => {
            this.$message.error(err.msg)
          })
      },
      // 客户列表
      getCustomer() {
        this.http
          .$post('admin/customer.api/list_customers', {
            company_id: this.userInfo.company_id
          })
          .then(res => {
            res.map(val => {
              this.customerList.push(val)
              this.formLabel[0].options.push({
                label: val.name,
                value: val.id
              })
            })
          })
          .catch(err => {
            this.$message.error(err.msg)
          })
      },
      // 产品列表
      getProduct() {
        this.http
          .$post('admin2/product.api/product_lists', {
            company_id: this.userInfo.company_id,
          })
          .then(res => {
            res.list.map(val => {
              this.productList.push(val)
            })
          })
          .catch(err => {
            this.$message.error(err.msg)
          })
      },
      // 弹窗产品列表
      getDialogProduct(isChange) {
        this.http
          .$post('admin/product.api/get_list', {
            curr: 0,
            limits: 0,
            customer_id: this.form.customer_id,
            company_id: this.userInfo.company_id
          })
          .then(res => {
            this.formLabel[1].options = []

            if (isChange) {
              if (this.form.product_id) {
                this.form.product_id = res.list[0].id
              }
            }
            res.list.map(val => {
              this.formLabel[1].options.push({
                label: val.name,
                value: val.id
              })
            })
          })
          .catch(err => {
            this.$message.error(err.msg)
          })
      },
      // 日期
      getDate() {
        let {listParams, dateValue} = this
        ;[listParams.start_time, listParams.end_time] = dateValue || []
        listParams.start_time /= 1000
        listParams.end_time /= 1000
        listParams.start_time = tools.formatDate(listParams.start_time)
        listParams.end_time = tools.formatDate(listParams.end_time)
        this.curr =1
        this.getOrderList()
      },
      // 选择客户
      choiceCustomer() {
        this.curr = 1
        this.getOrderList()
      },
      // 选择产品
      choiceProduct() {
        this.curr = 1
        this.getOrderList()
      },
      // 搜索
      search() {
        this.curr = 1
        this.getOrderList()
      },
      // 选择器
      formSelectChange(val) {
        if (val.prop == 'customer_id') {
          this.getContract()
          this.getDialogProduct(1)
        }
      },
      // 关联合同
      getContract() {
        this.http
          .$post('admin2/customer.api/customer_contract_list', {
            customer_id: this.form.customer_id
          })
          .then(res => {
            if (res.list.length) {
              res.list.map(val => {
                this.formLabel[5].options.push({
                  label: val.name,
                  value: val.id
                })
              })
            } else {
              this.formLabel[5].options = []
            }
          })
          .catch(err => {
            this.$message.error(err.msg)
          })
      },
      // 验证码确定
      defineCallback(code, vCode) {
        if (vCode == code) {
          // console.log('删除成功')
          this.http
            .$post('admin/order.api/set_status', {
              order_id: this.order_id,
              status: 2
            })
            .then(res => {
              this.getOrderList()
              this.$message({
                message: '删除成功',
                type: 'success'
              })
            })
            .catch(err => {
              this.$message.error(err.msg)
            })
          this.isShow = false
        } else {
          this.$message.error('验证码不正确')
        }
      },
      // 关闭
      canceled() {
        this.isShow = false
      }
    },
    created() {
      this.getOrderList()
      this.getCustomer()
      this.getProduct()
    },
    mounted() {
    }
  }
</script>
<style lang='less' scoped>
  /deep/ .el-dialog__header {
    border-bottom: 1px solid rgba(235, 235, 235, 1);
  }

  .order {
    margin: 0 auto;

    .container {
      background: #fff;
      padding: 30px 20px;
      .header {
        .dateSelect {
          padding-bottom: 20px;
        }

        .ipt {
          width: 20%;
          padding-right: 20px;
        }
        .result {
          background-color: rgba(230, 247, 255, 1);
          border: 1px solid rgba(145, 213, 255, 1);
          margin: 20px 0;
          color: #666;
          span {
            i {
              font-weight: 700;
            }
          }
        }
      }
    }
    .main {
      .gl-table {
        text-align: center;
      }
    }
  }

  .orderform {
    padding: 0 30px;
  }
</style>